package org.zjx.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class ServiceRegistry {
    private static final Logger logger = LoggerFactory.getLogger(ServiceRegistry.class);
    private final Map<String, Object> registeredServices = new ConcurrentHashMap<>();

    public void registerService(Class<?> interfaceClass, Object impl) {
        registeredServices.put(interfaceClass.getName(), impl);
        logger.info("Service registered: {}", interfaceClass.getName());
    }

    public void registerService(Object serviceImpl) {
        Class<?>[] interfaces = serviceImpl.getClass().getInterfaces();
        if (interfaces.length == 0) {
            logger.warn("Service implementation has no interfaces: {}", serviceImpl.getClass().getName());
            return;
        }
        for (Class<?> serviceInterface : interfaces) {
            registeredServices.put(serviceInterface.getName(), serviceImpl);
            logger.info("Service registered: {}", serviceInterface.getName());
        }
    }

    public Object getService(String className) {
        return registeredServices.get(className);
    }

    public boolean hasService(String serviceName) {
        return registeredServices.containsKey(serviceName);
    }

    public Set<String> getRegisteredServices() {
        return Set.copyOf(registeredServices.keySet());
    }

    public void clear() {
        registeredServices.clear();
    }
}